package com.common.library.ui.view;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import com.common.library.tools.DelayedTask;
import com.common.library.tools.Logger;

/**
 * @author txf
 * @Title 带点击效果的 LinearLayout
 * @package com.common.library.ui.view
 * @date 2017/6/9 0009
 */

public class ClickEffectLinearLayout extends LinearLayout implements DelayedTask.OnDelayedTaskListener {
    DelayedTask mDelayedTask;

    public ClickEffectLinearLayout(Context context) {
        super(context);
        init();
    }
    public ClickEffectLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public ClickEffectLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        mDelayedTask = new DelayedTask(this);
    }
    private OnClickListener l;
    public void addOnClickListener(OnClickListener l) {
        this.l = l;
    }
    @Override
    public void onHandleMessage(int msg) {
        Logger.i("收到延时任务消息 ");
        isAnim = true;
        startAnim(500, 1.0f, 0.0f);
    }

    public interface OnClickListener {
        void onClick();
    }
    float downY;
    boolean isAnim;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float startY = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = startY;
                Logger.i("ACTION_DOWN_Y : " + downY);
                isAnim = false;
                mDelayedTask.setOnDelayedTaskListener(this);
                mDelayedTask.startForwardTimer(150, 0);
                return true;
            case MotionEvent.ACTION_MOVE:
                return super.onTouchEvent(event);
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mDelayedTask.setOnDelayedTaskListener(null);
                mDelayedTask.stopForwardTimer();
                if (isAnim)
                    startAnim(500, 0.0f, 1.0f);
                Logger.i("ACTION_UPY : " + startY);
                if (l != null && Math.abs(downY - startY) < 200) {
                    l.onClick();
                }
                return true;
        }
        return true;
    }
    private void startAnim(int duration, float start, float end) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", start, end);
        anim.setDuration(duration);
        anim.start();
    }
}
